#!/usr/bin/env python
# _*_coding:utf-8 _*_
__author__ = "Gao"
from django.shortcuts import render
from django.shortcuts import redirect
from repoistory import models
from django.http import Http404
from ..libs.forms import AuthCreateForm
from ..libs.forms import AuthEditForm

def preview(request):
    '''Git账号表总揽'''
    if request.method == 'GET':
        res_dict = {'query_set':models.Auth.objects.all()}
        return render(request, 'backend/Auth/preview.html', res_dict)
    

def add(request):
    '''新增Git账号'''
    if request.method == 'GET':
        form_obj = AuthCreateForm()
    elif request.method == 'POST':
        form_obj = AuthCreateForm(request.POST)
        if form_obj.is_valid():
            models.Auth.objects.create(**form_obj.cleaned_data)
            return redirect('/backend/Auth/preview/')
    res_dict = {'form_obj': form_obj}
    return render(request, 'backend/Auth/change.html', res_dict)


def change(request, nid):
    '''修改Git账号'''
    auth_obj = models.Auth.objects.filter(id=nid).first()
    if not auth_obj:
        raise Http404
    if request.method == 'GET':
        initial = {'id': auth_obj.id,
                        'name': auth_obj.name,
                        'password': auth_obj.password}
        form_obj = AuthEditForm(initial=initial)
    elif request.method == 'POST':
        form_obj = AuthEditForm(request.POST)
        if form_obj.is_valid():
            auth_obj.name = form_obj.cleaned_data['name']
            auth_obj.password = form_obj.cleaned_data['password']
            auth_obj.save()
            return redirect('/backend/Auth/preview/')
    res_dict = {'form_obj': form_obj}
    return render(request, 'backend/Auth/change.html', res_dict)

